package com.offcn.servlet;

import com.offcn.entity.User;
import com.offcn.service.Impl.UserServiceImpl;
import com.offcn.service.UserService;
import com.offcn.utils.BaseServlet;
import com.offcn.utils.Page;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "UserServlet", urlPatterns = {"/UserServlet"})
public class UserServlet extends BaseServlet {
    //创建service对象，将username先传给service,再交给dao送至数据库进行查询是否由同名用户
    private UserService userService = new UserServiceImpl();


    protected void checkUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        System.out.println("checkUser:---"+username);
        User user = userService.getUser(username);
        System.out.println(user);
        if(user!=null){
            //有同名的，不能注册，提示用户已经存在
            response.getWriter().print(true);
        }else{
            response.getWriter().print(false);
        }
    }

    //退出功能，退出了就删除session,用户无法绕过登录界面去访问其他页面
    protected void doLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().invalidate();
        //跳转到index.jsp
        response.sendRedirect(request.getContextPath()+"/index.jsp");
    }

    //注册（添加user数据）
    protected void doRegist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取regist提交过来的数据
        String username = request.getParameter("username");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        /*注册之前，要进行表单验证（前台js完成），信息无误后检查数据库中是否存在用户名相同的（用户名设置了唯一），有相同就不给注册
        * 由当前servlet将Username一步步传到数据库查询，返回一个user对象，在这里检查user对象是否为空，如果为空代表数据库里没有同名user的用户，
        * 可以注册并添加到数据库中，否则就返回用户名已存在信息*/
        User user = userService.getUser(username);
        System.out.println(user);
        try {
            if(user==null){
                //数据库中没有同名的，可以注册，跳转注册成功  并回显注册成功的用户
                User user1 = new User(0, username, password, email);
                userService.addUser(user1);
                request.getSession().setAttribute("username",username);
                response.sendRedirect(request.getContextPath()+"/regist_success.jsp");
            }else{
                //有同名的，注册失败，跳转到注册页面，回显用户名已存在信息,并显示用户名，email
                request.getSession().setAttribute("errorMsg","用户名已存在");
                request.getSession().setAttribute("username",username);
                request.getSession().setAttribute("email",email);
                response.sendRedirect(request.getContextPath()+"/regist.jsp");
            }
        } catch (Exception e) {
            //注册异常(即添加的时候由于代码或其他问题产生中断导致注册失败)，回显注册异常提示
            request.getSession().setAttribute("errorMsg","注册异常，请重新注册");
            response.sendRedirect(request.getContextPath()+"/regist.jsp");
        }
    }

    //登录（查询user数据）
    protected void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取regist提交过来的数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        /*登录的时候要先判断查询出来的user是否为空，不为空在比对里面的数据，一致的就登陆成功*/
        User user = userService.getUser(username);
        try {
            if(user==null){
                //数据库中没有该user数据，直接登陆失败,回显错误信息
                request.getSession().setAttribute("errorMsg","该用户不存在，请检查用户名是否正确");
                response.sendRedirect(request.getContextPath()+"/login.jsp");

            }else{
                //不为空，继续判断内部数据是否正确
                if(password.equals(user.getPassword())){
                    //信息正确，跳转至登陆成功界面,回显用户名，存入user对象
                    request.getSession().setAttribute("user",user);
                    response.sendRedirect(request.getContextPath()+"/login_success.jsp");
                }else{
                    //信息不正确，跳转至登录界面，回显错误提示
                    request.getSession().setAttribute("user",user);
                    request.getSession().setAttribute("errorMsg","密码错误");
                    response.sendRedirect(request.getContextPath()+"/login.jsp");
                }

            }
        } catch (Exception e) {
            //登录异常(即添加的时候由于代码或其他问题产生中断导致注册失败)，回显登录异常提示
            request.getSession().setAttribute("errorMsg","登录异常，请重新登录");
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        }
    }


    //分页查询user数据并显示
    protected void getUserList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取由前台送来的pageNo
        String pageNo = request.getParameter("pageno");
        Page<User> userList = userService.getUserList(pageNo);
        //将userList存到request中，转发到userList页面
        request.setAttribute("page",userList);
        request.getRequestDispatcher("/user/userList.jsp").forward(request,response);
    }

    //修改user信息，前台点击修改后，执行该方法，首先要将要修改的数据展示出来，重定向至编辑页面
    protected void getUserById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        获取id,pageNo
        String id = request.getParameter("id");
        String pageNo = request.getParameter("pageNo");
        

        User user = userService.getUserById(id);
        //将user对象交给编辑页面，并转发页面至编辑
        request.setAttribute("user",user);
        request.setAttribute("pageNo",pageNo);
        request.getRequestDispatcher("/user/user_edit.jsp").forward(request,response);
    }


    protected void updateUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取id,及输入的其他信息 如果是添加，id为null
        String id = request.getParameter("id");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String tel = request.getParameter("tel");
        User user = new User(0, username, password, email, tel);
        int pageNo = Integer.parseInt(request.getParameter("pageNo"));
        System.out.println("UserServlet--update-pageNo:"+pageNo);


        if(id!=null && !id.equals("")){
            //是修改，调用修改方法即可
            try {
                userService.updateUser(id,username,password,email);
                //修改成功，回显信息，转发至分页查询页面
                request.getSession().setAttribute("msg",username+"修改成功");
                response.sendRedirect(request.getContextPath()+"/UserServlet?way=getUserList&pageno="+pageNo);
            } catch (Exception e) {
                //修改异常
                request.getSession().setAttribute("msg",username+"修改异常");
                response.sendRedirect(request.getContextPath()+"/UserServlet?way=getUserList&pageno="+pageNo);
            }
        }else{
            //是添加

            userService.addUser(user);
            //添加成功，回显信息，转发至分页查询页面
            request.getSession().setAttribute("msg",username+"添加成功");
            response.sendRedirect(request.getContextPath()+"/UserServlet?way=getUserList&pageno="+pageNo);
        }


    }

    //删除User数据
    protected void deleteUserById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取id
        String id = request.getParameter("id");
        int pageNo = Integer.parseInt(request.getParameter("pageNo"));
        String username = request.getParameter("username");
        try {
            userService.deleteUserById(id);
            //删除成功，数据回显，重定向至分页查询页面
            request.getSession().setAttribute("msg",username+"删除成功");
            response.sendRedirect(request.getContextPath()+"/UserServlet?way=getUserList&pageno="+pageNo);
        } catch (Exception e) {
            //删除异常，数据回显，重定向至分页查询页面
            request.getSession().setAttribute("msg",username+"删除异常");
            response.sendRedirect(request.getContextPath()+"/UserServlet?way=getUserList&pageno="+pageNo);
        }
    }

}
